package network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

import controller.Controller;

import model.Call;
import model.Model;

public class TCPServer extends Thread {

	private ServerSocket serverSocket = null;
	private Socket socket = null;

	public TCPService tcpService;
	private Controller controller;
	
	public TCPServer(InetAddress inetAddress, int port,Controller controller){
	 try {
		 this.controller=controller;
		serverSocket = new ServerSocket(port);
		//System.out.println("serversocket dans le TCPServer : " +serverSocket.getInetAddress().toString());
		System.out.println("[TCPServer] Creation d'un TCPServer sur le port : "+port+" (not run yet)");
		
	} catch (IOException e) {
		JOptionPane.showMessageDialog(null,
				"Error : applicative TCP port : "+port+" is already binded", "Error",
				JOptionPane.ERROR_MESSAGE);
		
		e.printStackTrace();
		System.exit(0);
	}
	}
	
	public void run() {
		System.out.println("[TCPServer] running (waiting for connection)");
		try {
			while(true){
			socket = serverSocket.accept();
			System.out.println("[TCPServer] Reception d'une demande, création d'un TCPService");
			tcpService = new TCPService(new Call(),socket, "TCPService du Receptionneur",controller);
			tcpService.start();
			
			}
		} catch (IOException e) {
			
			System.err.println("Erreur serveur");
		}
		finally{
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}